package com.cwj.jmh;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * @author chenwujie
 * @date 2021-03-09 13:32
 */
public class ExchangerTest {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        Thread t1 = new Thread("t1") {
            @Override public void run() {
                try {
                    String data = exchanger.exchange(Thread.currentThread().getName() + "t1");
                    System.out.println("t1.data : " + data);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("t1被中断");
                }
            }
        };
        t1.start();
        //
        //        TimeUnit.SECONDS.sleep(1);
        //        t1.interrupt();

        Thread t2 = new Thread("t2") {
            @Override public void run() {
                String data = "";
                for (int i = 0; i < 10000000; i++) {
                    data += i;
                }

                try {
                    String exchange = exchanger.exchange(data);
                    System.out.println("t2.data : " + exchange);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("t2被中断");
                }
            }
        };
        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();
    }
}
